#!/usr/bin/python
from VideoCapture import Device
import time, string, os
from PIL import Image

## Specify the amount of seconds to wait between individual captures.
interval = 1
threshold = 1000
hour = 3000
mins = 1
secs = 10
maxtime = 3600*hour+60*mins+secs

## If you get horizontal stripes or other errors in the captured picture
## (especially at high resolutions), try setting showVideoWindow=0.
#cam = Device(devnum=0, showVideoWindow=1)
cam = Device(devnum=0, showVideoWindow=0)

## Using the separate programs "setPropertiesDev0/1.pyw" before capturing
## works better for some devices.
## On the other hand, some devices don't remember their state, so the
## properties have to be set at every program start.
cam.displayCapturePinProperties()
#cam.displayCaptureFilterProperties()

print "press 'ctrl + c' to terminate"

i = 0

starttime = time.time()
endtime = starttime+maxtime

def before(sometime):
    if time.time() < sometime:
        return True
    else:
        return False

def check(old, new):
    """check(old, new) -> boolean

    Returns 1 if file1 differs from file2.  1 is also returned if one file or
    both files are not found.  Use this function only for small files, because
    no optimisation is done so the whole files are read into the memory.
    """
    try:
        f1 = open(old, 'rb')
    except IOError:
        return True
    try:
        f2 = open(new, 'rb')
    except IOError:
        f1.close()
        return True
    im1 = f1.read()
    im2 = f2.read()
    f1.close()
    f2.close()
    try:
        im1 = Image.open(old)
        im2 = Image.open(new)
        im1.thumbnail((12,12))
        im2.thumbnail((12,12))
        seq1 = im1.tostring()
        seq2 = im2.tostring()
        seq = []
        for i in range(len(seq1)):
            seq.append(abs(ord(seq1[i])-ord(seq2[i])))
        summ = sum(seq)
        print old + " to " + new +" diff is "+ str(summ)

        if summ > threshold:
            return True
        print "Not much diff found...",
        try:
            os.remove(new)
            print new + " is deleted"
        except IOError:
            print "but can't be deleted~~~(it can't happen) ! "
        return False
    except IOError:
        try:
            os.remove(new)
            print new + " is deleted, because it is not an image"
        except IOError:
            print "but can't be deleted~~~ ! "
        return False
    
prevfile = ""
while before(endtime):
    now = time.time()
    lasttime = now + interval
    filename = string.zfill(str(i),4) +'.jpg'
    print 'save to '+filename
    cam.saveSnapshot(string.zfill(str(i), 4) + '.jpg', timestamp=0, boldfont=0)
    i += 1
    while before(lasttime):
        time.sleep(0.1)
    if check(prevfile, filename):
        print 'got new pic: '+filename
        prevfile = filename

del cam
